<?php
header("Content-type: text/html; charset=utf-8");
date_default_timezone_set('PRC');
$aa = new AutoTtester();
$aa->testAction();

/**
 * 测试接口
 * @author dem
 *
 */
class AutoTtester
{
    
    function testAction(){
        $vcode = $_GET['vcode'];
        $username = $_GET['uname'];
        $passwd = $_GET['pwd'];
        $userType = 2;
        
        $date = urlencode(date("l M d Y",time()));
        header('X-Accel-Buffering: no'); // 关键是加了这一行。
        //cookie 保存目录
        $cookie_jar =__DIR__.'/cookie/'."{$username}.cookie";
        $loginUrl = 'http://urdt.cn:9998/';
        //模拟登录
        $loginData = [
            '__VIEWSTATE'=>'/wEPDwULLTEzMDM3NTU1NjBkZBhf1dJHrB+C3/1o0/et8ec3sGMm3kDf4cXS228RXwAu',
            '__VIEWSTATEGENERATOR'=>'C2EE9ABB',
            '__EVENTVALIDATION'=>'/wEdAAyFNZdVRh4VoLHO/P2BIH14Y3plgk0YBAefRz3MyBlTcDPSlu16Yx4QbiDU+dddK1N1czP4tIzn+z/OwzXVca/top4oRunf14dz2Zt2+QKDEG0kWP0ndUqHt2zDLd14pCnVizgKih7MwNg1PehQbQToIBxXVHYUg4lfVuETpqR0n834O/GfAV4V4n0wgFZHr3chnb8gfpR2v6dlLZGnyPxNiKlbKjN9ItObAVMK57kbBT9YyyR4qjX0bKJ2X6bXV1PwZkLcrDQ6cjZ+mGY27xxzENfevlmI9qLdrvrQVaRGtw==',
            'txtUserName'=>$username,
            'txtPwd'=>$passwd,
            'ddlType'=>$userType,
            'btnLogin'=>'',
            'txtLoginName'=>'',
            'txtDM'=>'',
            'txtFR'=>'',
            'zhjg'=>'',
            'zhfr'=>''
        ];
 	   $this->setUserCookie($loginUrl, $cookie_jar, $loginData);
        
        $userInfo =   $this->analysisCookie($cookie_jar);
        if($userInfo==false)
            exit('login fail');
        
        echo '<br/>登录成功<br/>';
        echo '用户信息:'.urldecode($userInfo['info']);
       
        $intVcode = intval($vcode);
        //检查视频是否可观看
        $dopostdata = ['Vcode'=>$vcode];
        echo '<br/>检查视频'.$vcode.'是否可以观看<br/>';
        $checkVedio =  $this->doAjax("http://urdt.cn:9998/StudentClass/shipinSection.aspx/CheckCanWatch?dt={$date}", $dopostdata, $cookie_jar,true);
        echo '<br/>检查结果<br/>';
        if($checkVedio['d']){
            exit($checkVedio['d']);
        }else{
            //可以看
        	echo '检查通过..模拟打开视频页面<br/>';
            //模拟打开视频网页
            $html = $this->getPage("http://urdt.cn:9998/StudentClass/WatchVideo.aspx?ids={$vcode}", $cookie_jar);
            sleep(2);
          
            //模拟提交我已看完
            $dopostdata = ['RVCode'=>$intVcode];
            $html2 = $this->doAjax("http://urdt.cn:9998/StudentClass/WatchVideo.aspx/UpdateStudyType?dt={$date}", $dopostdata,$cookie_jar,true);
            echo '模拟提交我已看完结果：'.$html['d'].'<br/>';
            
            //模拟弹出答题
            $html = $this->getPage("http://urdt.cn:9998/EntpClass/Example.aspx?id={$intVcode}", $cookie_jar);
            
            //模拟答题
            $html2 =  $this->doAjax("http://urdt.cn:9998/EntpClass/Xtyl1.ashx?cid=7&vid=1&uid=1000&c=Thu%20Jul%2019%202018%2013:33:28%20GMT+0800%20(%E4%B8%AD%E5%9B%BD%E6%A0%87%E5%87%86%E6%97%B6%E9%97%B4)", [],$cookie_jar,true);
            
            
            $html3 = $this->doAjax("http://urdt.cn:9998/EntpClass/Xtyl1.ashx?classid={$intVcode}&uid={$userInfo['userid']}&c=Thu%20Jul%2019%202018%2013:33:33%20GMT+0800%20(%E4%B8%AD%E5%9B%BD%E6%A0%87%E5%87%86%E6%97%B6%E9%97%B4)", [],$cookie_jar,true,$userInfo,$vcode);
            echo $vcode.'观看完毕 '.'<br/>';
        }
        
        
      /*   $this->getPage("http://urdt.cn:9998/StudentClass/shipinSection.aspx", $cookie_jar);
        $this->getPage("http://urdt.cn:9998/StudentClass/WatchVideo.aspx?ids=00002", $cookie_jar);
        $endVideo=['RVCode'=>'00002'];
        $this->doPost("http://urdt.cn:9998/WatchVideo.aspx/UpdateStudyType?dt=".urlencode("Wed Jul 04 2018"),$endVideo ,$cookie_jar,true); */
        exit;
        
    }
    
    private function getPage($url,$cookie_jar){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,0);
        curl_setopt($ch, CURLOPT_NOBODY, false);//设定是否输出页面 内容
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_jar);
        curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_jar.'.login');
        $html=curl_exec($ch);
        curl_close($ch);
        return $html;
        
    }
    
    private function setUserCookie($url,$cookie_jar,$loginParams){
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_NOBODY, false);//设定是否输出页面 内容
        curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_jar);
        curl_setopt($ch,CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch,CURLOPT_POSTFIELDS, $loginParams); //提交查询信息
        $content = curl_exec($ch);
        curl_close($ch);
        return $content;
        
    }
    
    private function  doPost($url,array $post ,$cookie_jar,$is_json=false){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
       
        if($is_json==true){
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_HEADER, ['contentType: application/json; charset=utf-8']);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post,JSON_UNESCAPED_UNICODE));
            curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36');
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,30);
        }else{
            curl_setopt($ch, CURLOPT_HEADER, false);
        }  curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
        
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        
        curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_jar);
        $result=curl_exec($ch);
        error_log('red'.$result);
        curl_close($ch);
    }
    
    function  analysisCookie($cookieFile){
        $cookies = [];
        if(file_exists($cookieFile)){
            $content = file_get_contents($cookieFile);
            if(!$content)
                return false;
            
                $content = explode(PHP_EOL, $content);
                $sessionId =explode("\t", $content[4]) ;
                $cookies['session'] = $sessionId[5].'='.$sessionId[6];
                for ($i=5;$i<count($content);$i++){
                    if(isset($content[$i])&&$content[$i]){
                        $temp = explode("\t", $content[$i]);
                        $cookies[$temp[5]] = $temp[6];
                    }
                }
                return $cookies;
        }
        return false;
    }
    private function  doAjax($url,array $data ,$cookie_jar,$is_json=false,$cookieInfo=[],$vcode=''){
        $date =urlencode(date('Y-m-d H:i:s',time()-5000));
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_COOKIEFILE,$cookie_jar);
        $header=['Content-Type:application/json; charset=UTF-8'];
        if($header){
            curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        }
        if (!empty($data)&&$is_json==false){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
        }else{
            if($data){
                curl_setopt($curl, CURLOPT_POST, 1);
                curl_setopt($curl, CURLOPT_POSTFIELDS,json_encode($data,JSON_UNESCAPED_UNICODE));
            }
        }
       
        curl_setopt($curl, CURLOPT_COOKIEJAR, $cookie_jar);
        if($cookieInfo)
        error_log("{$cookieInfo['session']}; userid={$cookieInfo['userid']}; info={$cookieInfo['info']}; url=http%3A//urdt.cn%3A9998/StudentClass/WatchVideo.aspx%3Fids%3D{$vcode}; checkUid={$cookieInfo['userid']}; st=0001/1/1%200%3A00%3A00; id={$vcode}; totaltime=2423; Start={$date}; nowtime=2423");
        if($cookieInfo)
        curl_setopt($curl, CURLOPT_COOKIE, "{$cookieInfo['session']}; userid={$cookieInfo['userid']}; info={$cookieInfo['info']}; url=http%3A//urdt.cn%3A9998/StudentClass/WatchVideo.aspx%3Fids%3D{$vcode}; checkUid={$cookieInfo['userid']}; st=0001/1/1%200%3A00%3A00; id={$vcode}; totaltime=6; Start={$date}; nowtime=6");
        else 
        curl_setopt($curl, CURLOPT_COOKIEFILE, $cookie_jar);
        
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        $error = curl_error($curl);
        error_log('post end:'.$output);
        curl_close($curl);
        return json_decode($output,true);
        
        
    }
}

